// ==================== 配置管理功能 ====================

// 获取所有配置
async function getConfigs() {
    const data = await chrome.storage.local.get(['configs']);
    return data.configs || [];
}

// 保存所有配置
async function saveConfigs(configs) {
    await chrome.storage.local.set({ configs });
}

// 添加或更新配置
async function saveCurrentConfig() {
    const name = document.getElementById('configName').value.trim();
    const sourceUrl = document.getElementById('sourceUrl').value.trim();
    const targetUrl = document.getElementById('targetUrl').value.trim();
    
    if (!name) {
        alert('请输入配置名称');
        return;
    }
    if (!sourceUrl || !targetUrl) {
        alert('请输入源地址和目标地址');
        return;
    }
    
    const configs = await getConfigs();
    const existingIndex = configs.findIndex(c => c.name === name);
    
    const config = {
        id: existingIndex >= 0 ? configs[existingIndex].id : Date.now(),
        name,
        sourceUrl,
        targetUrl,
        createdAt: existingIndex >= 0 ? configs[existingIndex].createdAt : Date.now(),
        updatedAt: Date.now()
    };
    
    if (existingIndex >= 0) {
        configs[existingIndex] = config;
    } else {
        configs.push(config);
    }
    
    await saveConfigs(configs);
    await renderConfigList();
    
    const statusEl = document.getElementById('status');
    statusEl.textContent = `✅ 配置"${name}"已保存`;
    statusEl.style.color = 'green';
    setTimeout(() => { statusEl.textContent = ''; }, 2000);
}

// 删除配置
async function deleteConfig(id) {
    if (!confirm('确定要删除这个配置吗？')) {
        return;
    }
    
    console.log('删除配置，ID:', id);
    let configs = await getConfigs();
    configs = configs.filter(c => c.id != id); // 使用 != 而不是 !==
    await saveConfigs(configs);
    await renderConfigList();
    
    const statusEl = document.getElementById('status');
    statusEl.textContent = '✅ 配置已删除';
    statusEl.style.color = 'green';
    setTimeout(() => { statusEl.textContent = ''; }, 2000);
}

// 加载配置到输入框
async function loadConfig(id) {
    console.log('加载配置，ID:', id);
    const configs = await getConfigs();
    console.log('所有配置:', configs);
    
    // 确保ID类型匹配（可能是数字或字符串）
    const config = configs.find(c => c.id == id); // 使用 == 而不是 ===
    
    if (config) {
        console.log('找到配置:', config);
        document.getElementById('configName').value = config.name;
        document.getElementById('sourceUrl').value = config.sourceUrl;
        document.getElementById('targetUrl').value = config.targetUrl;
        
        // 保存到storage，以便刷新后恢复
        await chrome.storage.local.set({
            currentConfigName: config.name,
            sourceUrl: config.sourceUrl,
            targetUrl: config.targetUrl
        });
        
        const statusEl = document.getElementById('status');
        statusEl.textContent = `📌 已加载配置"${config.name}"`;
        statusEl.style.color = '#2196F3';
        setTimeout(() => { statusEl.textContent = ''; }, 2000);
    } else {
        console.error('未找到配置，ID:', id);
    }
}

// 渲染配置列表
async function renderConfigList() {
    const configs = await getConfigs();
    const listEl = document.getElementById('configList');
    const emptyHint = document.getElementById('emptyHint');
    
    if (configs.length === 0) {
        listEl.innerHTML = '';
        emptyHint.style.display = 'block';
        return;
    }
    
    emptyHint.style.display = 'none';
    listEl.innerHTML = '';
    
    configs.forEach(config => {
        console.log('渲染配置:', config.name, 'ID:', config.id);
        const item = document.createElement('div');
        item.className = 'config-item';
        item.innerHTML = `
            <div class="config-name">📌 ${config.name}</div>
            <div class="config-url">源: ${config.sourceUrl}</div>
            <div class="config-url">目标: ${config.targetUrl}</div>
            <div class="config-actions">
                <button class="btn-secondary use-config-btn" data-id="${config.id}">使用</button>
                <button class="btn-danger delete-config-btn" data-id="${config.id}">删除</button>
            </div>
        `;
        listEl.appendChild(item);
        
        // 绑定事件监听器
        const useBtn = item.querySelector('.use-config-btn');
        const deleteBtn = item.querySelector('.delete-config-btn');
        
        if (useBtn && deleteBtn) {
            useBtn.addEventListener('click', () => {
                console.log('点击使用按钮，ID:', config.id);
                loadConfig(config.id);
            });
            deleteBtn.addEventListener('click', () => {
                console.log('点击删除按钮，ID:', config.id);
                deleteConfig(config.id);
            });
            console.log('事件监听器已绑定');
        } else {
            console.error('按钮未找到');
        }
    });
}

// ==================== Cookie显示功能 ====================

// 显示cookies详情的函数
function displayCookies(cookies) {
    const detailsEl = document.getElementById("cookieDetails");
    detailsEl.innerHTML = '';
    
    cookies.forEach(cookie => {
        const card = document.createElement('div');
        card.className = 'cookie-card';
        card.innerHTML = `
            <div class="cookie-name">🍪 ${cookie.name}</div>
            <div class="cookie-prop"><span>值:</span> ${cookie.value}</div>
            <div class="cookie-prop"><span>域名:</span> ${cookie.domain}</div>
            <div class="cookie-prop"><span>路径:</span> ${cookie.path}</div>
            <div class="cookie-prop"><span>HttpOnly:</span> ${cookie.httpOnly ? '✅ 是' : '❌ 否'}</div>
            <div class="cookie-prop"><span>Secure:</span> ${cookie.secure ? '✅ 是' : '❌ 否'}</div>
            <div class="cookie-prop"><span>SameSite:</span> ${cookie.sameSite || '无'}</div>
            <div class="cookie-prop"><span>过期时间:</span> ${cookie.expirationDate}</div>
        `;
        detailsEl.appendChild(card);
    });
}

// ==================== 页面初始化 ====================

// 页面加载时恢复保存的URL和状态
document.addEventListener("DOMContentLoaded", async () => {
    // 渲染配置列表
    await renderConfigList();
    
    const data = await chrome.storage.local.get(["currentConfigName", "sourceUrl", "targetUrl", "lastStatus", "lastStatusColor", "lastTime", "lastCookies"]);
    
    // 恢复配置名称
    if (data.currentConfigName) {
        document.getElementById("configName").value = data.currentConfigName;
    }
    
    if (data.sourceUrl) {
        document.getElementById("sourceUrl").value = data.sourceUrl;
    }
    if (data.targetUrl) {
        document.getElementById("targetUrl").value = data.targetUrl;
    }
    
    // 恢复上次的状态信息
    if (data.lastStatus) {
        const statusEl = document.getElementById("status");
        const timeDiff = Date.now() - (data.lastTime || 0);
        const timeStr = timeDiff < 60000 ? "刚刚" : `${Math.floor(timeDiff / 60000)}分钟前`;
        statusEl.textContent = `[${timeStr}] ${data.lastStatus}`;
        statusEl.style.color = data.lastStatusColor || "green";
        
        // 如果有保存的cookies，显示切换按钮
        if (data.lastCookies && data.lastCookies.length > 0) {
            displayCookies(data.lastCookies);
            document.getElementById("cookieToggle").style.display = "block";
        }
    }
    
    // 添加输入框的change事件监听器，自动保存
    document.getElementById("sourceUrl").addEventListener("change", async (e) => {
        await chrome.storage.local.set({ sourceUrl: e.target.value.trim() });
        console.log("源地址已保存:", e.target.value.trim());
    });
    
    document.getElementById("targetUrl").addEventListener("change", async (e) => {
        await chrome.storage.local.set({ targetUrl: e.target.value.trim() });
        console.log("目标地址已保存:", e.target.value.trim());
    });
    
    document.getElementById("configName").addEventListener("change", async (e) => {
        await chrome.storage.local.set({ currentConfigName: e.target.value.trim() });
        console.log("配置名称已保存:", e.target.value.trim());
    });
});

// ==================== 按钮事件监听 ====================

// 保存配置按钮
document.getElementById("saveConfigBtn").addEventListener("click", saveCurrentConfig);

// 检测登录状态
async function checkLoginStatus(sourceUrl) {
    return new Promise((resolve) => {
        chrome.runtime.sendMessage(
            { action: "checkLoginStatus", sourceUrl },
            (response) => {
                resolve(response);
            }
        );
    });
}

// 复制Cookies按钮
document.getElementById("copyBtn").addEventListener("click", async () => {
    const sourceUrl = document.getElementById("sourceUrl").value.trim();
    const targetUrl = document.getElementById("targetUrl").value.trim();
    const statusEl = document.getElementById("status");
    statusEl.textContent = "正在检测登录状态...";
    statusEl.style.color = "#666";

    if (!sourceUrl || !targetUrl) {
        statusEl.textContent = "请输入源地址和目标地址";
        statusEl.style.color = "orange";
        return;
    }

    // 先检测登录状态
    const loginStatus = await checkLoginStatus(sourceUrl);
    console.log("登录状态检测结果:", loginStatus);
    
    if (!loginStatus.loggedIn) {
        statusEl.textContent = `⚠️ ${loginStatus.reason}，请先登录`;
        statusEl.style.color = "#ff9800";
        document.getElementById("loginBtn").style.display = "block";
        return;
    }
    
    statusEl.textContent = "登录状态正常，正在复制cookies...";
    statusEl.style.color = "#666";

    chrome.runtime.sendMessage({ action: "copyCookies", sourceUrl, targetUrl }, async (resp) => {
        const currentTime = Date.now();
        
        if (resp?.success) {
            const message = resp.message || `成功复制 ${resp.count} 个 cookies`;
            statusEl.textContent = `${message} ✅`;
            statusEl.style.color = "green";
            console.log("复制成功:", message);
            
            // 隐藏登录按钮
            document.getElementById("loginBtn").style.display = "none";
            
            // 显示cookies详情
            if (resp.cookies && resp.cookies.length > 0) {
                displayCookies(resp.cookies);
                document.getElementById("cookieToggle").style.display = "block";
            }
            
            // 保存状态
            await chrome.storage.local.set({ 
                lastStatus: message + " ✅",
                lastStatusColor: "green",
                lastTime: currentTime,
                lastCookies: resp.cookies
            });
        } else {
            const errorMsg = resp?.error || "未知错误";
            statusEl.textContent = `失败: ${errorMsg} ❌`;
            statusEl.style.color = "red";
            console.error("Cookie 复制错误:", errorMsg);
            
            // 隐藏cookies详情
            document.getElementById("cookieToggle").style.display = "none";
            document.getElementById("cookieDetails").style.display = "none";
            
            // 如果需要登录，显示登录按钮
            if (resp?.needLogin) {
                document.getElementById("loginBtn").style.display = "block";
                statusEl.textContent = `⚠️ ${errorMsg}\n请先登录源地址`;
            }
            
            // 保存错误状态
            await chrome.storage.local.set({ 
                lastStatus: `失败: ${errorMsg} ❌`,
                lastStatusColor: "red",
                lastTime: currentTime
            });
        }
    });
});

// 打开源地址登录
document.getElementById("loginBtn").addEventListener("click", () => {
    const sourceUrl = document.getElementById("sourceUrl").value.trim();
    if (sourceUrl) {
        chrome.tabs.create({ url: sourceUrl });
    }
});

// 切换cookies详情显示/隐藏
document.getElementById("cookieToggle").addEventListener("click", () => {
    const detailsEl = document.getElementById("cookieDetails");
    const toggleBtn = document.getElementById("cookieToggle");
    
    if (detailsEl.style.display === "none" || !detailsEl.style.display) {
        detailsEl.style.display = "block";
        toggleBtn.textContent = "📋 隐藏Cookies详情";
    } else {
        detailsEl.style.display = "none";
        toggleBtn.textContent = "📋 查看Cookies详情";
    }
});
